<template>
	<view class="container">
		<view class="imgbox" v-if="weixin && $Route.query.orderNum">
			<image class="img" src="@/public/images/public/mask.png" mode="widthFix"></image>
			<button type="warn" class="btn complete" @tap="checkHaveOrder(true)">已完成支付宝付款</button>
			<button type="default" class="btn cancel" @tap="goBack()">取消支付并返回</button>
		</view>
		<view v-else class="form">
		</view>
	</view>
</template>

<script>
	import { decrypt, encrypt } from "@/utils/common/encrypt.js"
	export default {
		data() {
			return {
				orderModel: null,
			}
		},
		computed: {
			weixin() {
				return this.isWeixin()
			}
		},
		onLoad(e) {
			//获取支付完成后的订单数据
			console.log(e);

			//拦截支付完成后跳转来的请求，提示用户返回微信
			let isFromWx = uni.getStorageSync('isFromWx')
			if(isFromWx && !this.weixin && !this.$Route.query.isFromWx){
				uni.removeStorageSync('isFromWx')
				//显示提示按钮
				uni.showModal({
					title: '支付提示',
					content: '请返回微信查看支付结果',
					showCancel: false,
					success: () => {}
				})
				return
			}
			//拦截支付完成后跳转来的请求
			
			//拦截从微信跳转来的请求，非微信下进行支付
			if(this.$Route.query.isFromWx && this.$Route.query.orderNum){
				//非微信下正式下单交易
				if(!this.weixin){
					this.orderForWx(this.$Route.query.orderNum)
				}
				return
			}
			//拦截从微信跳转来的请求
			
			//读取本地订单数据
			console.log(this.$Route.query.orderModel);
			if(this.$Route.query.orderModel){
				uni.setStorageSync('orderModel', JSON.stringify(this.$Route.query.orderModel))
				this.orderModel = this.$Route.query.orderModel
			}else{
				let orderModel = uni.getStorageSync('orderModel')
				if(orderModel){
					this.orderModel = JSON.parse(orderModel)
				}
			}
			//读取本地订单数据
			
			//根据本地订单数据下单
			if(!this.orderModel){
				console.log('参数错误');
				uni.showModal({
					title: '错误提示',
					content: '数据请求错误，请返回重试',
					showCancel: false,
					success: () => {
						this.$Router.replace({name: 'userrecharge'})
					}
				})
			}else{
				//判断浏览器
				if(!this.weixin){
					//非微信下进行下单支付流程
					this.createOrder()
				}else{
					//微信下预交易下单
					this.createOrderFromWx()
				}
			}
			//根据本地订单数据下单
		},
		onShow() {
			//用户支付过程中强制返回时触发
			let isFromWx = uni.getStorageSync('isFromWx') 
			if(!this.weixin && !isFromWx && !this.$Route.query.isFromWx ){
				this.checkHaveOrder()
			}
			if(!this.weixin && isFromWx){
				//显示提示按钮
				uni.showModal({
					title: '支付提示',
					content: '请返回微信查看支付结果',
					showCancel: false,
					success: () => {}
				})
				return
			}
		},
		methods: {
			//检查是否已有订单
			checkHaveOrder(force=false) {
				let haveOrder = uni.getStorageSync('haveOrder')
				if(haveOrder || force){
					//删除本地记录，防止重复提示
					uni.removeStorageSync('haveOrder')
					//formdata支付完成后通过返回URL参数获取，或者从本地存储获取
					let formdata = uni.getStorageSync('formdata')
					if(formdata){
						let out_trade_no = JSON.parse(formdata).out_trade_no
						uni.showModal({
							title: '支付提示',
							content: '查询到未支付订单，请确认是否已完成支付',
							confirmText: '已支付',
							cancelText: '未支付',
							success: (res) => {
								if(res.confirm){
									//验证支付结果
									this.checkOrderStatus(out_trade_no)
								}
							},
							complete: () => {
								uni.removeStorageSync('orderModel')
								//uni.removeStorageSync('formdata')
							}
						})
					}else{
						uni.showToast({
							title: '没有找到您的充值记录',
							icon: 'error',
							duration: 1500
						})
						setTimeout(()=>{
							this.$Router.replace({name: 'userrecharge'})
						}, 1500);
					}
				}
			},
			//支付完成检测
			checkOrderStatus(orderNum) {
				this.$http.get({
					url: '/api/userRechargeRecord/verifyPayResult',
					data: {
						orderNum
					},
				}).then(data => {
					console.log(data)
					if(data.success && data.code == 200 && data.result){
						console.log('验证通过后进入成功页面');
						uni.showToast({
							title: data.message,
							icon: 'success',
							duration: 1000
						});
						this.$ShowToast({text: data.message});
						this.$store.dispatch('updateUserinfo');
						setTimeout(()=>{
							this.$Router.replace({name: 'userrecharge', params: {success: 1}})
						}, 1000);
					}else{
						uni.showModal({
							title: '支付提示',
							content: '您的充值支付未成功，如果您已完成支付，请联系公众号“彩虹有料”进行处理。',
							showCancel: false,
							success: (res) => {
								if(res.confirm){
									uni.setClipboardData({
										data: '彩虹有料'
									});
									this.$Router.replace({name: 'userrecharge'})
								}
							}
						})
					}
				}).catch((err) => {
					console.log(err);
					this.$ShowToast({text: '系统错误，请稍后重试', type: 2})
				})
			},
			//非微信下统一下单支付
			createOrder() {
				this.$http.post({
					url: '/api/userRechargeRecord/createOrder',
					data: {
						...this.orderModel
					},
				}).then(data => {
					console.log(data)
					if(data.success && data.result){
						//保存支付宝返回数据，用于校验订单是否支付
						let formdata = data.result.split('value="')[1].split('">')[0]
						formdata = this.htmlchars_decode(formdata)
						uni.setStorageSync('formdata', formdata)
						
						//保存支付请求记录
						uni.setStorageSync('haveOrder', true)
						//h5非微信，直接跳转打开支付宝
						document.querySelector('body').innerHTML = data.result
						document.forms[0].submit()
					}else{
						console.log(data.message)
						this.payError('订单创建失败，请返回充值页面重试')
						this.$ShowToast({text: data.message || '系统错误，请返回重试', type: 2})
					}
				}).catch((err) => {
					console.log(err)
					this.payError('订单创建失败，请返回充值页面重试')
					this.$ShowToast({text: '系统错误，请返回重试', type: 2})
				})
			},
			//微信下完成下单并跳转
			createOrderFromWx() {
				this.$http.post({
					url: '/api/userRechargeRecord/createOrder',
					data: {
						...this.orderModel
					},
				}).then(data => {
					console.log(data)
					if(data.success && data.result){
						//保存支付宝返回数据，用于校验订单是否支付
						let formdata = data.result.split('value="')[1].split('">')[0]
						formdata = this.htmlchars_decode(formdata)
						uni.setStorageSync('formdata', formdata)
						
						//保存支付请求记录
						uni.setStorageSync('haveOrder', true)
						setTimeout(()=>{
							//订单信息加密，浏览器携带加密信息跳转
							let orderNum = encrypt(data.result)
							this.$Router.replace({ path: '/pay/alipay', query: { orderNum, isFromWx: 1 }})
						}, 200)
					}else{
						console.log(data.message)
						this.payError('订单创建失败，请返回充值页面重试')
						this.$ShowToast({text: data.message || '系统错误，请返回重试', type: 2})
					}
				}).catch((err) => {
					console.log(err)
					this.payError('订单创建失败，请返回充值页面重试')
					this.$ShowToast({text: '系统错误，请返回重试', type: 2})
				})
			},
			//非微信下请求支付
			orderForWx(orderNum){
				//保存来源信息
				uni.setStorageSync('isFromWx', true)
				
				//读取订单信息
				let orderCode = decrypt(orderNum)
				console.log(orderCode);
				
				//保存支付请求记录
				uni.setStorageSync('haveOrder', true)
				//h5非微信，直接跳转打开支付宝
				document.querySelector('body').innerHTML = orderCode
				document.forms[0].submit()
			},
			//支付失败
			payError(content) {
				//清理本地缓存数据
				uni.removeStorageSync('haveOrder')
				uni.removeStorageSync('orderModel')
				uni.removeStorageSync('formdata')
				//提示返回充值页面
				uni.showModal({
					title: '支付提示',
					content: content,
					showCancel: false,
					success: (res) => {
						if(res.confirm){
							this.$Router.replace({name: 'userrecharge'})
						}
					}
				})
			},
			//检测浏览器类型
			isWeixin() {
				let ua = navigator.userAgent.toLowerCase();
				if (ua.match(/micromessenger/i) == "micromessenger"){
					return true
				}else{
					return false
				}
			},
			// html实体转义
			htmlchars_decode(str) {
				str = str.replace(/&nbsp;/g, ' ');
				str = str.replace(/&amp;/g, '&');
				str = str.replace(/&lt;/g, '<');
				str = str.replace(/&gt;/g, '>');
				str = str.replace(/&quot;/g, '"');
				str = str.replace(/&apos;/g, "'");
				str = str.replace(/&#039;/g, "'");
				return str;
			},
			//返回充值页面
			goBack() {
				uni.showModal({
					title: '支付提示',
					content: '请确认是否取消支付并返回？',
					success: (res) => {
						if(res.confirm){
							//清理本地缓存
							uni.removeStorageSync('haveOrder')
							uni.removeStorageSync('orderModel')
							uni.removeStorageSync('formdata')
							this.$Router.replace({name: 'userrecharge'})
						}
					}
				})
			}
		}
	}
</script>

<style lang="scss" >
	.container{
		padding: 0;
		height: 100vh;
		width: 100vw;
		.imgbox{
			height:100%;
			width: 100%;
			position: fixed;
			left: 0;
			top: 0;
			background: rgba(0,0,0,.5);
			box-sizing: border-box;
			padding: 10rpx 50rpx;
			text-align: center;
			image{
				width: 100%;
			}
			.btn{
				width: 90%;
				margin-top: 180rpx;
				border-radius: 40rpx;
				line-height: 80rpx;
				&.cancel{
					margin-top: 50rpx;
				}
			}
		}
	}
</style>